#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    string decodeString(string s) {
        stack<string> stk;
        string res;
        int i = 0, n = s.size();
        while (i < n)
        {
            string cnt;
            while (s[i] >= '0' && s[i] <= '9')
            {
                cnt += s[i++];
            }
            stk.push(cnt);
            string m = { s[i] };
            string tmp;
            if (s[i] != ']')
                stk.push(m);
            else
            {
                string tmp;
                while (stk.size())
                {
                    string k = stk.top(); stk.pop();
                    if (k == "[")
                        break;
                    tmp += k;
                }
                int t = stoi(stk.top()); stk.pop();
                string str;
                while (t--)
                {
                    str += tmp;
                }
                stk.push(str);
            }
            i++;
        }
        while (stk.size())
        {
            res += stk.top(); stk.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};